import router from '@/router'
import store from '@/store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from './auth'
import { isRelogin } from './request'

NProgress.configure({ showSpinner: false })

export async function routerBefore(whiteList, to, from, next) {
    // -----进入路由前拦截函数-------
    NProgress.start()

    let loginParams = null;
    //从链接中获取隐藏导航栏和侧边栏的参数
    let isNoShowLayout = localStorage.getItem("isNoShowLayout");
    if (to.query.isNoShowLayout || isNoShowLayout) {
        store.commit("app/SET_NOSHOWLAYOUT", true);
        localStorage.removeItem("isNoShowLayout");
    }

    //单点登录拦截逻辑
    if (!getToken() || window.HC_config.VUE_APP_SSO_IGNORE_TOKEN) {
        let token = to.query[window.HC_config.VUE_APP_SSO_TOKEN_NAME || "code"];
        if (token) {
            let data = { code: token, orgId: to.query.orgId }
            let ssoPropConfig = window.HC_config.VUE_APP_SSO_PROP_CONFIG;
            if (ssoPropConfig)
            {
                data = {};
                let params = ssoPropConfig.split(",");
                if (params && params.length != 0)
                {
                    params.forEach(preProp=>{
                        if (preProp)
                        {
                            data[preProp] = to.query[preProp];
                        }
                    })
                }
            }
            try {
                let res = await store.dispatch('user/LoginByCode', data);
                if (res)
                {
                    console.log("=================cs",res)
                }
            } catch (err) {
                debugger
                console.error(err);
                let errData = err.data;
                if (window.HC_config.VUE_IS_SSO && errData && errData.redirect_uri)
                {
                    location.href = errData.redirect_uri;
                    return;
                }
            }
        }
    }

    // 菏泽门户单点登录逻辑
    if (!getToken() || window.HC_config.VUE_APP_SSO_IGNORE_TOKEN)
    {
        if (to.query.ticket)
        {
            let data = {
                ticket: to.query.ticket
            }
            try {
                await store.dispatch('user/LoginByClientId', data)
                delete to.query.ticket;
            } catch (err) {
                console.error(err);
            }
        }
    }

    //
    //ip登录拦截逻辑
    if (!getToken() || window.HC_config.VUE_APP_SSO_IGNORE_TOKEN) {
        if (to.query.clientIp) {
            try {
                await store.dispatch('user/LoginByClientIp', { client_ip: to.query.clientIp });
            } catch (err) {
                console.error(err);
            }
        }
    }

    // 待办跳转
    if ((!getToken() || window.HC_config.VUE_APP_SSO_IGNORE_TOKEN) && to.query.secretKey) {
        try {
            console.log(to.query)
            await store.dispatch('user/GoBacklogBySecretKey',
                { secretKey: to.query.secretKey },
                {
                    path: to.path,
                    query: {
                        formType: to.query.formType,
                        moduleName: to.query.moduleName,
                        sourceUrl: to.query.sourceUrl,
                        unid: to.query.unid
                    }
                });
        } catch (err) {
            console.error(err);
        }
    }

    //加密用户名登录 逻辑
    let sk = to.query.sk;
    if (sk) {
        let userMsg = window.atob(sk)
        if (userMsg) {
            loginParams = JSON.parse(userMsg);
            try {
                await store.dispatch('user/LoginBySSO', {
                        secretKey: loginParams.key,
                        username: loginParams.username,
                    })
                    // next(loginParams.path)
                    // next({ path: loginParams.path })
                    // NProgress.done()
            } catch (err) {
                console.error(err);
            }
        }
    }

    //菏泽临时门户登录
    const hzcode = to.query.hzcode;
    if(hzcode){
        try {
            const params = JSON.parse(atob(hzcode));
            await store.dispatch('user/HzLoginByPassword',params);
            delete to.query.hzcode;
        } catch (error) {
            console.error(error);
        }
    }

    if (getToken()) {
        to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
            /* has token*/
        if (to.path === '/login') {
            if(window.HC_config.APP_ROUTE_FIRST){
                next({path: window.HC_config.APP_ROUTE_FIRST, replace: true })
            }else{
                next({ path: '/' })
            }
            NProgress.done()
        } else {
            if (!store.getters.userInfo || !store.getters.userInfo.unid) {
                isRelogin.show = true
                // 判断当前用户是否已拉取完user_info信息
                store.dispatch('user/GetInfo').then(() => {
                    isRelogin.show = false
                    if(to.path.toLowerCase() === '/mhindex'){
                        store.dispatch('GenerateRoutes').then(accessRoutes => {
                            router.addRoutes(accessRoutes) // 动态添加可访问路由表
                        })
                        next({...to, replace: true })
                    }else{
                        store.dispatch('GenerateRoutes').then(accessRoutes => {
                            router.addRoutes(accessRoutes) // 动态添加可访问路由表
                            // 根据roles权限生成可访问的路由表
                            if (!loginParams) {
                                next({...to, replace: true })
                            } else {
                                next({ path: loginParams.path })
                            }
                        })
                    }
                }).catch(err => {
                    store.dispatch('user/LogOut').then(() => {
                        Message.error(err)
                        next({ path: '/' })
                        // let template_url = localStorage.getItem("currentRoter");
                        // if(template_url){
                        //     next({path:`template_url`})
                        // }else{
                        //     next({path:`/login`})
                        // }
                    })
                })

            } else {
                next()
            }
        }
    }
    else {
        // 没有token
        if (whiteList.indexOf(to.path) !== -1) {
            // 在免登录白名单，直接进入
            next()
        } else {
            if (to.query.isNoShowLayout) {
                localStorage.setItem("isNoShowLayout", true);
            }
            if (to.query.sso_redirect_url) {
                localStorage.setItem("sso_redirect_url", to.query.sso_redirect_url);
            }
            if (window.HC_config.VUE_IS_SSO) {
                location.href = window.HC_config.VUE_SSO_URL;
            } else {
                next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
            }
            NProgress.done()
        }
    }
}

export function routerAfter() {
    NProgress.done()
}

// 将路由跳转挂职到woindow上
window.pushRouter = (path, query) => {
    router.push(path, query);
}
